package cn.tedu.store.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.tedu.store.service.ICartService;
import cn.tedu.store.util.ResponseResult;
import cn.tedu.store.vo.CartVO;
/**
 * 处理购物车数据相关的请求的控制器类
 * @author Administrator
 *
 */
@RestController
@RequestMapping("carts")
public class CartController extends BaseController {
	
	@Autowired
	private ICartService cartService;
	
	@RequestMapping("add_to_cart")
	public ResponseResult<Void> addToCart(Long gid,Integer num,HttpSession session){
		//从Session中获取uid和username
		Integer uid = getUidFromSession(session);
		String username = getUsernameFromSession(session);
		//执行添加到购物车
		cartService.addToCart(uid, gid, num, username);
		return new ResponseResult<Void>(SUCCESS);
	}
	
	@GetMapping("/")
	public ResponseResult<List<CartVO>> listByUid(HttpSession session){
		Integer uid = getUidFromSession(session);
		List<CartVO> data = cartService.getByUid(uid);
		for(CartVO c:data) {
			System.out.println(c.getCid());
		}
		return new ResponseResult<List<CartVO>>(SUCCESS,data);
		
	}
	
	@RequestMapping("{cid}/add")
	public ResponseResult<Integer> addNum(
			@PathVariable("cid") Integer cid,
			HttpSession session
			){
		
		Integer uid=getUidFromSession(session);
		String username=getUsernameFromSession(session);
		Integer data = cartService.addNum(cid, uid, username);
		return new ResponseResult<Integer>(SUCCESS,data);
		
	}
	
	@RequestMapping("{cid}/reduce")
	public ResponseResult<Integer> reduceNum(
			@PathVariable("cid") Integer cid,
			HttpSession session
			){
		
		Integer uid=getUidFromSession(session);
		String username=getUsernameFromSession(session);
		Integer data = cartService.reduceNum(cid, uid, username);
		return new ResponseResult<Integer>(SUCCESS,data);
		
	}

	@GetMapping("get_by_cids")
	public ResponseResult<List<CartVO>> getByCids(
			Integer[] cids,HttpSession session
			){
		//从Session中获取uid
		Integer uid = getUidFromSession(session);
		//调用业务层对象执行
		List<CartVO> data = cartService.getByCids(cids, uid);
		//返回成功
		return new ResponseResult<List<CartVO>>(SUCCESS,data);
		
	}
	
}
